package com.yuerenjf.yuerenjinfu.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.qiniu.android.common.Zone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.utils.StringUtils;
import com.umeng.analytics.MobclickAgent;
import com.yuerenjf.yuerenjinfu.R;
import com.yuerenjf.yuerenjinfu.bean.OwnSettingBean;
import com.yuerenjf.yuerenjinfu.dialog.DialogPicSelector;
import com.yuerenjf.yuerenjinfu.dialog.DialogProgress;
import com.yuerenjf.yuerenjinfu.http.Constants;
import com.yuerenjf.yuerenjinfu.http.Xutils;
import com.yuerenjf.yuerenjinfu.utils.CacheUtils;
import com.yuerenjf.yuerenjinfu.utils.CommonUtils;
import com.yuerenjf.yuerenjinfu.utils.ConstantUtils;
import com.yuerenjf.yuerenjinfu.utils.DataCleanManager;
import com.yuerenjf.yuerenjinfu.utils.MyDisplayImageOptions;
import com.yuerenjf.yuerenjinfu.utils.UtilsImageProcess;
import com.yuerenjf.yuerenjinfu.widget.CircleImageView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class SettingActivity extends BaseActivity implements View.OnClickListener {

    private RelativeLayout rl_setting_upload;
    private RelativeLayout rl_setting_code;
    private RelativeLayout rl_setting_qrcode;
    private RelativeLayout rl_setting_idcard;
    private RelativeLayout rl_setting_bank;
    private RelativeLayout rl_setting_loginpwd;
    private RelativeLayout rl_setting_withdrawpwd;
    private RelativeLayout rl_setting_findpwd;
    private RelativeLayout rl_setting_help;
    private RelativeLayout rl_setting_quit;
    private RelativeLayout rl_setting_about;
    private RelativeLayout rl_setting_cleancache;
    private RelativeLayout pingguLayout;

    private TextView tv_setting_code;
    private TextView tv_user_idcard;
    private TextView tv_setting_bank;
    private TextView tv_setting_cache;
    private CircleImageView iv_setting_head;
    private TextView pingguText;

    private DialogProgress progress;


    OwnSettingBean.DataBean mDataBean;
    String qiniu_token;
    DialogPicSelector mCameraPathDialog;

    boolean isNeedUpdate;
    private String realname;

    public static void launchActivity(Context context) {
        Intent intent = new Intent(context, SettingActivity.class);
        context.startActivity(intent);
    }

    boolean isRegisterSuccessFrom;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        tv_title.setText("设置中心");
        ll_back.setOnClickListener(this);

        if (getIntent().hasExtra("type")) {
            isRegisterSuccessFrom = true;
        } else {
            isRegisterSuccessFrom = false;
        }

        getSettingData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);

        if (isNeedUpdate) {
            isNeedUpdate = false;
            getSettingData();
        }


    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected View getChildView() {

        View view = View.inflate(this, R.layout.activity_setting, null);

        rl_setting_upload = (RelativeLayout) view.findViewById(R.id.rl_setting_upload);
        rl_setting_code = (RelativeLayout) view.findViewById(R.id.rl_setting_code);
        rl_setting_qrcode = (RelativeLayout) view.findViewById(R.id.rl_setting_qrcode);
        rl_setting_idcard = (RelativeLayout) view.findViewById(R.id.rl_setting_idcard);
        rl_setting_bank = (RelativeLayout) view.findViewById(R.id.rl_setting_bank);
        rl_setting_loginpwd = (RelativeLayout) view.findViewById(R.id.rl_setting_loginpwd);
        rl_setting_withdrawpwd = (RelativeLayout) view.findViewById(R.id.rl_setting_withdrawpwd);
        rl_setting_findpwd = (RelativeLayout) view.findViewById(R.id.rl_setting_findpwd);
        rl_setting_help = (RelativeLayout) view.findViewById(R.id.rl_setting_help);
        rl_setting_quit = (RelativeLayout) view.findViewById(R.id.rl_setting_quit);
        rl_setting_about = (RelativeLayout) view.findViewById(R.id.rl_setting_about);
        rl_setting_cleancache = (RelativeLayout) view.findViewById(R.id.rl_setting_cleancache);
        pingguLayout = (RelativeLayout) view.findViewById(R.id.rl_setting_fengxian_layout);

        pingguText = (TextView) view.findViewById(R.id.setting_pinggu_text);

        tv_setting_code = (TextView) view.findViewById(R.id.tv_setting_code);
        tv_user_idcard = (TextView) view.findViewById(R.id.tv_user_idcard);
        tv_setting_bank = (TextView) view.findViewById(R.id.tv_setting_bank);
        tv_setting_cache = (TextView) view.findViewById(R.id.tv_setting_cache);
        iv_setting_head = (CircleImageView) view.findViewById(R.id.iv_setting_head);

        pingguLayout.setOnClickListener(this);
        rl_setting_upload.setOnClickListener(this);
        rl_setting_code.setOnClickListener(this);
        rl_setting_qrcode.setOnClickListener(this);
        rl_setting_idcard.setOnClickListener(this);
        rl_setting_bank.setOnClickListener(this);
        rl_setting_loginpwd.setOnClickListener(this);
        rl_setting_withdrawpwd.setOnClickListener(this);
        rl_setting_findpwd.setOnClickListener(this);
        rl_setting_help.setOnClickListener(this);
        rl_setting_quit.setOnClickListener(this);
        rl_setting_about.setOnClickListener(this);
        rl_setting_cleancache.setOnClickListener(this);

        if (CacheUtils.getString(this, ConstantUtils.SP_SECRET).equals("")) {
            startActivity(new Intent(this, LoginActivity.class));
        } else {
            getQiniuToken(null);

        }
        return view;
    }

    private void setCacheSize() {
        try {
            tv_setting_cache.setText(DataCleanManager.getTotalCacheSize(SettingActivity.this));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getSettingData() {


        final Map<String, String> map = new HashMap<String, String>();
        map.put("signature", CacheUtils.getString(SettingActivity.this, ConstantUtils.SP_SIGNATURE));
        map.put("uid", CacheUtils.getString(SettingActivity.this, ConstantUtils.SP_UID));
        Xutils.getInstance().post(SettingActivity.this, Constants.URL_OWN_SETTING, map, new Xutils.XCallBack() {
            @Override
            public void onResponse(String result) {
                Gson gson = new Gson();
                OwnSettingBean bean = gson.fromJson(result, OwnSettingBean.class);
                mDataBean = bean.getData();
                if (mDataBean != null) {
                    ImageLoader.getInstance().displayImage(mDataBean.getAvatar(), iv_setting_head, MyDisplayImageOptions.getInstance(R.drawable.icon_header_default));
                    tv_setting_code.setText(mDataBean.getInvite_code());
                    if (StringUtils.isNullOrEmpty(mDataBean.getBank_status())) {
                        tv_setting_bank.setText("去开户");
                    } else {
                        tv_setting_bank.setText(mDataBean.getBank_status());
                    }

                    if (StringUtils.isNullOrEmpty(mDataBean.getCard_id_show())) {
                        tv_user_idcard.setText("");
                    } else {
                        tv_user_idcard.setText(mDataBean.getCard_id_show());
                    }


                    if (StringUtils.isNullOrEmpty(mDataBean.getRisk())) {
                        pingguText.setText("去测试");
                    } else {
                        pingguText.setText(mDataBean.getRisk());
                    }
                    realname = mDataBean.getRealname();
                }

            }

            @Override
            public void onFailer(int status, String result) {

            }

            @Override
            public void onFinish() {

            }
        });


    }

    private void getQiniuToken(final Bitmap bitmap) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("signature", CacheUtils.getString(SettingActivity.this, ConstantUtils.SP_SIGNATURE));
        map.put("uid", CacheUtils.getString(SettingActivity.this, ConstantUtils.SP_UID));
        Xutils.getInstance().post(SettingActivity.this, Constants.URL_GET_QINIUTOKEN, map, new Xutils.XCallBack() {
            @Override
            public void onResponse(String result) {
                Log.i("result", result);
                if (result == null) {
                    return;
                }
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    qiniu_token = jsonObject.getString("data");
                    if (bitmap != null) {
                        uploadQiNiu(bitmap);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailer(int status, String result) {

            }

            @Override
            public void onFinish() {
            }
        });


    }

    @Override
    public void onClick(View v) {
        if (mDataBean == null) {
            Toast.makeText(SettingActivity.this, "网络请求加载失败", Toast.LENGTH_SHORT).show();
            return;
        }
        switch (v.getId()) {

            case R.id.rl_setting_fengxian_layout:
                WebActivity.launchActivity(SettingActivity.this, mDataBean.getRisk_url());
                break;


            case R.id.rl_setting_upload:
                mCameraPathDialog = new DialogPicSelector(this);
                mCameraPathDialog.showCustomDialog();
                mCameraPathDialog.setCallBack(new DialogPicSelector.TypeCallBack() {
                    @Override
                    public void setImageToView(Bitmap bitmap) {
                        iv_setting_head.setImageBitmap(bitmap);
                        uploadPic(bitmap);
                    }
                });
                break;
            case R.id.rl_setting_code:
                MyCodeActivity.launchActivity(SettingActivity.this, mDataBean.getInvite_code(), mDataBean.getQrcode());
                break;
            case R.id.rl_setting_qrcode:
                MyCodeActivity.launchActivity(SettingActivity.this, mDataBean.getInvite_code(), mDataBean.getQrcode());
//                startWebActivity(ConstantUtils.SETTING_QRCODE);
                break;
            case R.id.rl_setting_idcard:
//                UserAuthActivity.launchActivity(SettingActivity.this, realname, mDataBean.getCard_id_show(), mDataBean.getBank_status());
                isNeedUpdate = true;
                WebActivity.launchActivity(SettingActivity.this, mDataBean.getAuthen_url());

                break;
            case R.id.rl_setting_bank:
                isNeedUpdate = true;
                WebActivity.launchActivity(SettingActivity.this, mDataBean.getAuthen_url());
//                UserAuthActivity.launchActivity(SettingActivity.this, realname, mDataBean.getCard_id_show(), mDataBean.getBank_status());
                break;
            case R.id.rl_setting_loginpwd:

                RePasswordActivity.launchActivity(SettingActivity.this);

                break;
            case R.id.rl_setting_withdrawpwd:

                break;
            case R.id.rl_setting_help:
                WebActivity.launchActivity(SettingActivity.this, Constants.URL_HELP_CENTER);
                break;
            case R.id.rl_setting_quit:

                //    通过AlertDialog.Builder这个类来实例化我们的一个AlertDialog的对象
                AlertDialog.Builder builder = new AlertDialog.Builder(SettingActivity.this);
                //    设置Title的内容
                builder.setTitle("提示");
                //    设置Content来显示一个信息
                builder.setMessage("确定退出登录");
                //    设置一个PositiveButton
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        CacheUtils.delString(SettingActivity.this, ConstantUtils.SP_UID);
                        CacheUtils.delString(SettingActivity.this, ConstantUtils.SP_SECRET);
                        CacheUtils.delString(SettingActivity.this, ConstantUtils.SP_WEB_SIGNATURE);
                        CacheUtils.delString(SettingActivity.this, ConstantUtils.SP_SIGNATURE);

                        CommonUtils.showToast(SettingActivity.this, "退出成功");
                        finish();
                        Intent intent = new Intent(SettingActivity.this, MainActivity.class);
                        intent.putExtra("current", "0");
                        startActivity(intent);
                    }
                });
                //    设置一个NegativeButton
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                //    显示出该对话框
                builder.show();


                break;
            case R.id.ll_back:

                if (isRegisterSuccessFrom) {
                    Intent main = new Intent(SettingActivity.this, MainActivity.class);
                    startActivity(main);
                } else {
                    finish();
                }

                break;
            case R.id.rl_setting_about:
                WebActivity.launchActivity(SettingActivity.this, Constants.URL_ABOUT_US);
//                startActivity(new Intent(this, AboutActivity.class));
                break;
            case R.id.rl_setting_cleancache:
                DataCleanManager.cleanApplicationData(this);
                CommonUtils.showToast(this, "清除成功");
//                setCacheSize();
                break;
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (mCameraPathDialog != null) {
            mCameraPathDialog.activityForResult(requestCode, resultCode, data);
        }
        if(resultCode==1001){
            finish();
        }

    }

    private void uploadHeadImage(String key) {
        Map<String, String> map = new HashMap<String, String>();
        String uid = CacheUtils.getString(SettingActivity.this, ConstantUtils.SP_UID);
        String secret = CacheUtils.getString(SettingActivity.this, ConstantUtils.SP_SECRET);
        String signature = CommonUtils.md5(CommonUtils.md5(CacheUtils.getString(SettingActivity.this, ConstantUtils.SP_TOKEN) + key + uid) + secret);
        map.put("signature", signature);
        map.put("uid", uid);
        map.put("path", key);
        Xutils.getInstance().post(SettingActivity.this, Constants.URL_SETTING_AVATAR, map, new Xutils.XCallBack() {
            @Override
            public void onResponse(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String data = jsonObject.getString("data");
                    Toast.makeText(SettingActivity.this, "上传成功", Toast.LENGTH_SHORT).show();

                    if (mCameraPathDialog != null && mCameraPathDialog.isShowing()) {
                        mCameraPathDialog.dismiss();
                        mCameraPathDialog = null;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void onFailer(int status, String result) {

            }

            @Override
            public void onFinish() {

            }
        });


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (mCameraPathDialog != null) {
            mCameraPathDialog.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


    private void uploadPic(Bitmap bitmap) {
        progress = new DialogProgress(this);
        progress.show();
        if (StringUtils.isNullOrEmpty(qiniu_token)) {
            getQiniuToken(bitmap);
        } else {
//            String filePath = UtilsImageProcess.getPath(bitmap);
            uploadQiNiu(bitmap);
        }


    }


    private void uploadQiNiu(Bitmap bitmap) {
        String filePath = UtilsImageProcess.getPath(bitmap);
        if (filePath == null) {
            return;
        }
        Configuration configuration = new Configuration.Builder()
                .chunkSize(256 * 1024)  //分片上传时，每片的大小。 默认 256K
                .putThreshhold(512 * 1024)  // 启用分片上传阀值。默认 512K
                .connectTimeout(10) // 链接超时。默认 10秒
                .responseTimeout(60) // 服务器响应超时。默认 60秒
//                .recorder(recorder)  // recorder 分片上传时，已上传片记录器。默认 null
//                .recorder(recorder, keyGen)  // keyGen 分片上传时，生成标识符，用于片记录器区分是那个文件的上传记录
                .zone(Zone.zone0) // 设置区域，指定不同区域的上传域名、备用域名、备用IP。默认 Zone.zone0
                .build();
        // 重用 uploadManager。一般地，只需要创建一个 uploadManager 对象
        UploadManager uploadManager = new UploadManager(configuration);

        // 重用 uploadManager。一般地，只需要创建一个 uploadManager 对象
//        UploadManager uploadManager = new UploadManager();
        uploadManager.put(filePath, null, qiniu_token,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        //  res 包含hash、key等信息，具体字段取决于上传策略的设置。
                        if (progress != null && progress.isShowing()) {
                            progress.dismiss();
                        }
                        try {
                            key = res.getString("key");
                            uploadHeadImage(key);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, null);

    }


}
